package com.jiang.dianping;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 模拟高并发
public class HttpClientExample implements Runnable {

    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        URL url = new URL("http://localhost:8080/api/shop/1");
        ExecutorService executorService = Executors.newFixedThreadPool(100);

        for (int i = 0; i < 100; i++) {
            Thread.sleep(1);
            HttpClientExample clientExample = new HttpClientExample();
            executorService.execute(clientExample);
        }

        executorService.shutdown();
    }

    @Override
    public void run() {
        try {
            URL url = new URL("http://localhost:8080/api/shop/1");
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(String.valueOf(url));
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity content = response.getEntity();
            String responseBody = "";
            if (content != null) {
                responseBody = EntityUtils.toString(content);
            }
            System.out.println("Response: " + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
